import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, Affix, Alert, message, Modal} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {
    PAGE,
    TABLE,
    FORM_BIG_OPTIONS,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
    ROWSELECTION_FIXED_COLUMN_WIDTH,
} from '../constants';
import WrappedSelect from '../common/WrappedSelect';
import {PERMISSION} from './constants';
import routes from './routes';
import {baseDataStatus} from '../Enum';
import {Link} from 'react-router-dom';
import {hasPermissions, conventSorter, getObjById} from './utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {conventEnumValueToString} from '../utils';
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
import difference from 'lodash/difference';
import WrappedTag from '../common/WrappedTag';
import styles from './style.css';
import PWCSelectPanel from './PartWarrantyCategory/SelectPanel';
import ImportPanel from './ImportPanel';
class QueryPanel extends React.PureComponent {
    state = {
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
        showTags: false,
        showPanel: false,
        showImportPanel: false,
    };

    showPanel = () => {
        this.setState({showPanel: !this.state.showPanel});
    }

    toggleShowTags = () => {
        this.setState({
            showTags: !this.state.showTags
        });
    };


    onConfirm = () => {
        if(!this.state.selectedRowKeys.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'workItemPanel.validate.invoice',
                defaultMessage: '选择的备件不能为空'
            }));
        this.setState({showPanel: true});
    }

    onSubmit = (data = {}) => {
        if(!this.state.selectedRowKeys.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'workItemPanel.validate.invoice',
                defaultMessage: '选择的备件不能为空'
            }));
        this.setState({
            loading: true
        });
        this.props.onSelectBatch(this.state.selectedRowKeys, data.id).then(success => {
            if(success)
                return this.setState({
                    loading: false,
                    showPanel: false,
                    selectedRowKeys: [],
                    selectedRows: [],
                });
            return this.setState({
                loading: false,
            });
        });
    };

    onClearAll = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: [],
        });
        this.props.onChangeBatch();
    };

    onDelete = id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    };

    onSelectChange = (selectedRowKeys, selectedRows) => {
        const data = this.state.selectedRows;
        const preSelectedKeys = this.state.selectedRowKeys; // 勾选行

        if(selectedRowKeys.length > preSelectedKeys.length)
            selectedRows.forEach(v => {
                if(data.findIndex(d => d.id === v.id) === -1) data.push(v);
            });
        else {
            // 取消勾选
            const diffKeys = difference(preSelectedKeys, selectedRowKeys);
            diffKeys.forEach(k => {
                const index = data.findIndex(d => d.id === k);
                data.splice(index, 1);
            });
        }
        this.setState({
            selectedRowKeys,
            selectedRows: data
        });
    };


    onCancel = () => {
        this.setState({
            currentId: '',
            showPanel: false
        });
    }

    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({
                ...conventSorter(sorter),
                pageIndex: PAGE.index
            });
    };
    onCloseImportPanel = () => {
        this.setState({
            showImportPanel: false
        });
    }
    onChangeBatch = () => {
        this.setState({
            showImportPanel: true
        });
    }
    onImportChange = data => {
        if(data)
            this.setState({
                showImportPanel: false
            });
    }
    render() {
        const operations = [];
        const otherBtns = [];
        if(hasPermissions(this.props.permissions, PERMISSION.batchCategory))
            otherBtns.push(
                <Button key={PERMISSION.batchCategory} onClick={this.onChangeBatch}>
                    {this.props.intl.formatMessage({
                        id: 'workItemPanel.btn.mode',
                        defaultMessage: '修改分类标准导入'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.assistUpdate) || hasPermissions(this.props.permissions, PERMISSION.assistAdd))
            otherBtns.push(
                <Button key="assist" href={`#${routes.assist.format()}`}>
                    {this.props.intl.formatMessage({
                        id: 'workItemPanel.btn.assist',
                        defaultMessage: '自定义辅料'
                    })}
                </Button>
            );
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.code',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'code',
                sorter: true,
                render: (text, record) => this.props.isBatch ? text : (
                    <Link key="detail" to={routes.detail.format(record.id)}>
                        {text}
                    </Link>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.name',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'name',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.description',
                    defaultMessage: '英文描述'
                }),
                dataIndex: 'description',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.length',
                    defaultMessage: '备件长度（mm）'
                }),
                dataIndex: 'length',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.width',
                    defaultMessage: '备件宽度（mm）'
                }),
                dataIndex: 'width',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.height',
                    defaultMessage: '备件高度（mm）'
                }),
                dataIndex: 'height',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.netWeight',
                    defaultMessage: '备件净重（kg）'
                }),
                dataIndex: 'netWeight',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.grossWeight',
                    defaultMessage: '备件毛重（kg）'
                }),
                dataIndex: 'grossWeight',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.usagePerCar',
                    defaultMessage: '每车用量'
                }),
                dataIndex: 'usagePerCar',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.partReplacementCode',
                    defaultMessage: '替代件'
                }),
                dataIndex: 'partReplacementCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(baseDataStatus, text)
            }
        ];
        let rowSelection = null;
        if(this.props.isBatch)
            rowSelection = {
                fixed: true,
                columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
                type: 'checkbox',
                getCheckboxProps: record => ({
                    disabled: !hasPermissions(record.options, PERMISSION.batchCategory)
                }),
                selectedRowKeys: this.state.selectedRowKeys,
                onChange: this.onSelectChange
            };
        else
            columns.push({
                title: this.props.intl.formatMessage({
                    id: 'workItemPanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [{
                        id: PERMISSION.update,
                        children: (
                            <Link key="setAssist" to={routes.update.format(r.id)}>
                                {this.props.intl.formatMessage({
                                    id: 'workItemPanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                    }];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            });
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };

        const pwcColums = [{
            title: this.props.intl.formatMessage({
                id: 'detail.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        const alertMessage = (
            <div>
                <span>
                    {this.props.intl.formatMessage({
                        id: 'workItemPanel.alertMessage.span',
                        defaultMessage: '已选择'
                    })}
                    <a onClick={this.toggleShowTags}>
                        {this.state.selectedRows.length}
                        {this.props.intl.formatMessage({
                            id: 'workItemPanel.alertMessage.a.number',
                            defaultMessage: '项'
                        })}
                    </a>
                    {this.props.intl.formatMessage({
                        id: 'workItemPanel.alertMessage.comma',
                        defaultMessage: '，'
                    })}
                    {this.props.intl.formatMessage({
                        id: 'workItemPanel.alertMessage.assignText',
                        defaultMessage: '可'
                    })}
                    <a
                        size="small"
                        type="primary"
                        onClick={this.onConfirm}>
                        {this.props.intl.formatMessage({
                            id: 'workItemPanel.btn.closeBtn',
                            defaultMessage: '修改分类标准'
                        })}
                    </a>
                </span>
                {this.state.showTags && (
                    <div className={styles.partTag}>
                        {this.state.selectedRows.map(r => (
                            <WrappedTag key={r.id} closable id={r.id} onClose={this.onDelete}>
                                {r.code}
                            </WrappedTag>
                        ))}
                    </div>
                )}
            </div>
        );
        return (
            <div>
                <Modal key="modal" visible={this.state.showPanel} title={this.props.intl.formatMessage({
                    id: 'dutyUnit.modal.title',
                    defaultMessage: '选择备件索赔分类'
                })} width={1000} maskClosable={false} footer={null} destroyOnClose={true} onCancel={this.showPanel}>
                    <PWCSelectPanel onSelect={this.onSubmit} columns={pwcColums} />
                </Modal>
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        selectKey={'1'}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'workItemPanel.form.code',
                                    defaultMessage: '编号'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.props.conditions.code}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'workItemPanel.form.name',
                                    defaultMessage: '名称'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="name"
                                    value={this.props.conditions.name}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'workItemPanel.form.status',
                                    defaultMessage: '状态'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <WrappedSelect
                                    name="status"
                                    allowClear
                                    value={this.props.conditions.status}
                                    options={baseDataStatus.toList(language)}
                                    onChange={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        {this.props.categoryName
                            ? <Col {...FORM_BIG_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'workItemPanel.form.category',
                                        defaultMessage: '分类'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    <WrappedTag className={styles.tagFontSize} color="blue"
                                        closable onClose={this.props.onCloseTag}>{this.props.categoryName}</WrappedTag>
                                </FormItem>
                            </Col> : null}
                    </Row>
                    <Row className="operation-buttons">
                        <Col span={10}>
                            <ButtonGroup>
                                <Button
                                    key="query"
                                    type="primary"
                                    onClick={this.props.querySearch}
                                    loading={this.props.loading}>
                                    {this.props.intl.formatMessage({
                                        id: 'workItemPanel.btn.query',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                            </ButtonGroup>
                            <Button key="clear" onClick={this.props.onClickReset}>
                                {this.props.intl.formatMessage({
                                    id: 'workItemPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                        {!this.props.isBatch &&
                            <Col span={14} className="col-align-right">
                                <ButtonGroup>{otherBtns}</ButtonGroup>
                                {operations}
                            </Col>}
                    </Row>

                    {this.props.isBatch && <Affix offsetTop={0} className={styles.alertMargin}><Row>
                        <Alert message={alertMessage} type="warning" closable showIcon
                            closeText={<span className={styles.closeText}>{this.props.intl.formatMessage({
                                id: 'workItemPanel.warning.closeText',
                                defaultMessage: '退出'
                            })}</span>} onClose={this.onClearAll} />
                    </Row></Affix>}
                    <Table
                        className="white-space-nowrap"
                        columns={columns}
                        dataSource={this.props.data}
                        rowKey="id"
                        rowSelection={rowSelection}
                        pagination={pagination}
                        loading={this.props.loading || this.state.loading}
                        onChange={this.onChangeSort}
                        locale={locale}
                        {...TABLE} />
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object,
    intl: PropTypes.object,
    loading: PropTypes.bool,
    permissions: PropTypes.array,
    querySearch: PropTypes.func,
    onChangeBatch: PropTypes.func,
    onClickReset: PropTypes.func,
    onConditionsChange: PropTypes.func,
    onConditionsPressEnter: PropTypes.func,
};
import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    tableSearch,
    categorySearch,
    changeBatch,
    onClickBatch,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);

const getCategoryName = createSelector(
    state => state.getIn(['page', 'domainData', 'categories', 'data']),
    state => state.getIn(['page', 'appState', 'queryCondition', 'partCategoryId']),
    (categories, categoryId) => {
        if(!categoryId)
            return '';
        const category = getObjById(categories.toJS(), categoryId);
        return category ? category.name : '';
    }
);

const mapStateToProps = state => ({
    conditions: getConditions(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    permissions: getPermissions(state),
    data: getData(state),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    categoryName: getCategoryName(state),
    isBatch: state.getIn(['page', 'appState', 'isBatch']),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (value, name) => dispatch(saveQueryCondition(name, value)),
    onConditionsPressEnter: (value, name) => {
        dispatch(saveQueryCondition(name, value));
        dispatch(querySearch());
    },
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onCloseTag: () => dispatch(categorySearch()),
    onChangeBatch: () => dispatch(changeBatch()),
    onSelectBatch: (ids, pid) =>
        dispatch(onClickBatch(ids, pid)).then(success => {
            if(success)
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
            
            return success;
        }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(QueryPanel));
